<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise-ajax</title>
</head>

<body>
    <button id="btn">ajax</button>
    <script>
        // 1. 获取按钮
        let btn = document.querySelector('button');
        btn.onclick = function () {
            let p = new Promise((resolve, reject) => {
                // xhr
                const xhr = new XMLHttpRequest();
                // 建立链接
                xhr.open('get', 'http://localhost:8000/json');
                // 设置结束数据的类型
                xhr.responseType = 'json';
                // 发送请求
                xhr.send();
                // 监听状态
                xhr.onreadystatechange = function () {
                    // 0- 4
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            // 响应体 成功返回响应体
                            resolve(xhr.response);
                        }else{
                            // 失败响应回状态码
                            reject('你失败了，你知道么？： ' + xhr.status)
                        }
                    }
                }
            })
            p.then(response=>{
                console.log(response);
            },reason=>{
                console.log(reason);
            })
        }
    </script>
</body>

</html>